# -*- coding: utf-8 -*-
import os
import io
import time
import requests
import pytesseract
from PIL import Image
from .result import result

HLJU_INDEX_URL='http://my.hlju.edu.cn/login.portal'
LOGIN_VCODE_URL='http://my.hlju.edu.cn/captchaGenerate.portal'
PASSWORD_VALIDATE_URL='http://my.hlju.edu.cn/userPasswordValidate.portal'

# 登录校园网
def login_hlju(uid,pwd):
    print('login begin login hlju')
    try:
        print('login in try...')
        index_cookie = request_index_cookie()

        # if dont get index cookie after 10 tried, i guess the network error
        if index_cookie == None:
            print('login index cookie is None')
            return result(105)

        login_result = None
        cookies={'JSESSIONID':index_cookie}
        for i in range(15):# try 10 times
            print('login count: ',i)
            if login_result != None:
            	break

            captcha = request_vcode(cookies)
            if captcha == None:
                continue

            param={'Login.Token1':uid,'Login.Token2':pwd,'captcha':captcha}

            login_result = login_school(uid,cookies,param)

        # if tried 10,result still be none, i guess uid or pwd error
        if login_result == None:
            return result(104)

        return result(100,login_result)
    except Exception as e:
    	print('login error:',e)
    	return result(105)

# 获取校园网主页的 cookie，用于请求验证码
def request_index_cookie():
    #这里需要注意，返回的 Set-Cookie 有两个值，应该取第二个
    try:
        result = None
        for i in range(10):
            print('login index count: ',i)
            if result != None:
                break
            cs = requests.get(HLJU_INDEX_URL,timeout=10).headers['Set-Cookie']
            print('cs is:',cs)
            result = cs.split(',')[1].split(';')[0].split('=')[1]

        return result
    except Exception as e:
        print('login request index cookie error:',e)
        return None

# 请求并解析验证码，返回验证码中的字符串，不稳定，需要多次尝试
def request_vcode(cookie):
    try:
        rv=requests.get(LOGIN_VCODE_URL,cookies=cookie,timeout=2)
        i = Image.open(io.BytesIO(rv.content))
        return pytesseract.image_to_string(i)
    except Exception as e:
        print('login vcode error:',e)
        return None

    # vcode_name=cookie.get('JSESSIONID')+'.png'

    # 下载验证码
    # with open(vcode_name,'wb') as f:
    # 	for chunk in rv.iter_content(1024):
    # 		f.write(chunk)
    #
    # # 读取验证码
    # fp=open(vcode_name,'rb')
    # try:
    #     result = pytesseract.image_to_string(Image.open(fp))
    # except Exception as e:
    #     return None
    #
    # # 删除验证码
    # os.remove(os.path.join(os.getcwd(),vcode_name))
    #
    # return result

# 带参数登录校园网,登录成功则返回 cookie，失败返回空字符串
def login_school(uid,cookies,param):
    print('login begin login')
    try:
        print('login in try')
        r = requests.post(PASSWORD_VALIDATE_URL,cookies=cookies,data=param,timeout=2)
    except Exception as e:
        print('login login school error')
        return None

    set_cookies = r.cookies
    if len(set_cookies) > 0:
        print('login cookie > 0')
        return [{'uid':uid,'token':set_cookies['iPlanetDirectoryPro']}]
    else:
    	return None

if __name__ == '__main__':
    # for i in range(100):
	print(login_hlju('20135081','147150'))
